package com.jusyl.cristo.auth;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.jusyl.cristo.auth.mapper.AuthOperationMapper;
import com.jusyl.cristo.auth.model.AuthUser;

public class CustomRealm extends AuthorizingRealm {
	@Autowired
	AuthOperationMapper mapper;

	/**
	 * 授权
	 * @param principalCollection
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		String userName = (String) principalCollection.getPrimaryPrincipal();
		List<String> permissionList=new ArrayList<String>();
		permissionList.add("user:add");
		permissionList.add("user:delete");
		if (userName.equals("zhou")) {
			permissionList.add("user:query");
		}
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
		info.addStringPermissions(permissionList);
		info.addRole("admin");
		return info;
	}

	/**
	 * 认证
	 * @param authenticationToken
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken at) throws AuthenticationException {
		String userName = (String) at.getPrincipal();
		
		AuthUser au  = mapper.getUserByName(userName);
		if(au == null) {
			throw new UnknownAccountException();
		}
		
		if(at.getCredentials().equals(DigestUtils.md5Hex(au.getPassword()))){
			throw new UnknownAccountException();
		}
		
		
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName, DigestUtils.md5Hex(au.getPassword()), this.getName());
		return info;
	}

}
